package com.mingmen.canting.gongyingshang;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.mingmen.canting.R;
import com.mingmen.canting.activity.LoginActivity;
import com.mingmen.canting.adapter.GongYIngAdapter;
import com.mingmen.canting.adapter.GongYingShangIndexAdapter;
import com.mingmen.canting.adapter.SearchAdapter;
import com.mingmen.canting.adapter.SearchSupplierAdapter;
import com.mingmen.canting.base.BaseBean;
import com.mingmen.canting.chushizhang.JingLiCompareActivity;
import com.mingmen.canting.definerecycleview.SwipeRecyclerView;
import com.mingmen.canting.defineview.ClearEditText;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.immersionbar.ImmersionBar;
import com.mingmen.canting.model.GongYIngCateGoryModel;
import com.mingmen.canting.model.GongYingListModel;
import com.mingmen.canting.model.SearchModel;
import com.mingmen.canting.model.SupplierSearchModel;
import com.mingmen.canting.popwindow.PopupWindowCompat;
import com.mingmen.canting.refresh.ClassicsFooter;
import com.mingmen.canting.refresh.ClassicsHeader;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.SharePreferenceUtil;
import com.mingmen.canting.util.UtilTool;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;

public class GongYingShangActivity extends FragmentActivity implements GongYingShangIndexAdapter.OnItemClickListener {
    @BindView(R.id.text_return)
    TextView textReturn;
    @BindView(R.id.linear_return)
    LinearLayout linearReturn;
    @BindView(R.id.text_center)
    TextView textCenter;
    @BindView(R.id.img_right)
    ImageView imgRight;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.mToolbar)
    Toolbar mToolbar;
    @BindView(R.id.recycle_list)
    RecyclerView recycle_list;
    GongYingShangIndexAdapter supplierDaTingAdapter;

    @BindView(R.id.layout_gongying)
    LinearLayout layout_gongying;

    @BindView(R.id.layout_compare)
    LinearLayout layout_compare;

    String token;

    List<GongYingListModel.DataBean> dataGongYingBeanList = new ArrayList<>();

    PopupWindowCompat popupWindow;
    GongYIngAdapter myLabelAdapter;

    @BindView(R.id.layout_cataGory)
    LinearLayout layout_cataGory;
    @BindView(R.id.text_Category)
    TextView text_Category;
    @BindView(R.id.btn_search)
    Button btn_search;
    @BindView(R.id.main_search)
    ClearEditText main_search;

    String categoryId = "";
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    int pageNumber = 1;
    int totalPage;
    @BindView(R.id.layout_alldata)
    LinearLayout layout_alldata;
    @BindView(R.id.layout_nodata)
    LinearLayout layout_nodata;
    @BindView(R.id.layout_serarch)
    LinearLayout layout_serarch;
    @BindView(R.id.layout_search)
    LinearLayout layout_search;
    String keyWord;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gongyingshang);
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);
        ImmersionBar.with(this).titleBar(mToolbar)
                .navigationBarColor(R.color.black).init();
        textCenter.setText("合作供应商");
        token = (String) SharePreferenceUtil.get(this, "token", "");
        recycle_list.setLayoutManager(new LinearLayoutManager(this));
        supplierDaTingAdapter = new GongYingShangIndexAdapter(this, dataGongYingBeanList);

        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.custom_divider));
        recycle_list.addItemDecoration(divider);
        recycle_list.setAdapter(supplierDaTingAdapter);
        getSupplierCategory();

        getCateList(token, "", "", pageNumber);
//        getAllList();

        refreshLayout.setRefreshHeader(new ClassicsHeader(GongYingShangActivity.this));
        refreshLayout.setRefreshFooter(new ClassicsFooter(GongYingShangActivity.this));

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                dataGongYingBeanList.clear();
                pageNumber = 1;

//                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                getCateList(token, "", "", pageNumber);
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (pageNumber >= totalPage) {
                    Toast.makeText(GongYingShangActivity.this, "已到最后一页", Toast.LENGTH_SHORT).show();
                    refreshlayout.finishLoadMore(false);//传入false表示加载失败
                } else {
                    pageNumber++;
                    getCateList(token, "", "", pageNumber);


                    refreshlayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
                }


            }
        });
        supplierDaTingAdapter.setOnItemClickListener(this);
        main_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                getCateList(token, "", main_search.getText().toString(), 1);
                keyWord = main_search.getText().toString();
                return false;
            }
        });
        main_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    keyWord = "";
                    getCateList(token, categoryId, keyWord, 1);

                }

            }
        });

    }

    List<GongYIngCateGoryModel.DataBean> dataBeanList = new ArrayList<>();

    //    供应商类别列表
    public void getCateList(String token, String categoryId, String keyword, int pageNumber) {
        HttpResponse.getSupplierByCategory(token, categoryId, keyword, pageNumber, new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {

                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (dataGongYingBeanList.size() > 0) {
                    dataGongYingBeanList.clear();
                }
                if (baseBean.getCode() == 0) {

                    GongYingListModel gongYingListModel = new GongYingListModel();
                    gongYingListModel = GsonUtil.GsonToBean(s, GongYingListModel.class);
                    totalPage = gongYingListModel.getTotalPage();
                    dataGongYingBeanList.addAll(gongYingListModel.getData());
                    if (dataGongYingBeanList.size() == 0) {
                        layout_alldata.setVisibility(View.GONE);
                        layout_nodata.setVisibility(View.VISIBLE);
//                        layout_cataGory.setVisibility(View.GONE);
                    } else {
                        layout_alldata.setVisibility(View.VISIBLE);
                        layout_nodata.setVisibility(View.GONE);
//                        layout_cataGory.setVisibility(View.VISIBLE);
                    }

                    supplierDaTingAdapter.setDataList(dataGongYingBeanList);
                    supplierDaTingAdapter.notifyDataSetChanged();

                } else if (baseBean.getCode() == 401) {
                    startActivity(new Intent(GongYingShangActivity.this, LoginActivity.class));
                    finish();
                } else {
                    Toast.makeText(GongYingShangActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onAfter(String s, Exception e) {
                super.onAfter(s, e);
                refreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                refreshLayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
            }
        });
    }

    public void getSupplierCategory() {
        HttpResponse.getSupplierCategory(token, new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (dataBeanList.size() > 0) {
                    dataBeanList.clear();
                }
                Log.d("dkdkdkdk", s);
                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    GongYIngCateGoryModel gongYIngCateGoryModel = new GongYIngCateGoryModel();
                    gongYIngCateGoryModel = GsonUtil.GsonToBean(s, GongYIngCateGoryModel.class);
                    GongYIngCateGoryModel.DataBean dataBean=new GongYIngCateGoryModel.DataBean();
                    dataBean.setId("");
                    dataBean.setName("全部");
                    dataBeanList.add(dataBean);
                    dataBeanList.addAll(gongYIngCateGoryModel.getData());
                    popWindowCreate(dataBeanList);
                } else if (baseBean.getCode() == 401) {
//                    startActivity(new Intent(GongYingShangActivity.this, LoginActivity.class));
//                    finish();
                } else {
                    Toast.makeText(GongYingShangActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                }


            }
        });
    }

    String cateGroy = "";

    @OnClick({R.id.text_return, R.id.linear_return, R.id.text_center, R.id.img_right, R.id.layout_gongying, R.id.layout_compare, R.id.layout_cataGory, R.id.btn_search})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {

            case R.id.text_return:
                finish();
                break;
            case R.id.linear_return:
                finish();
                break;
            case R.id.text_center:
                break;
            case R.id.img_right:
                break;
            case R.id.layout_gongying:
                intent = new Intent(GongYingShangActivity.this, SupplierDaTingActivity.class);
                intent.putExtra("categoryId", categoryId);
                intent.putExtra("cateGroy", cateGroy);
                startActivity(intent);
                break;
            case R.id.layout_compare:
                startActivity(new Intent(GongYingShangActivity.this, GongYingCompareActivity.class));
                break;
            case R.id.layout_cataGory:


                popupWindow.showAsDropDown(layout_cataGory);
                UtilTool.hideKeyboard(GongYingShangActivity.this, layout_cataGory);

                break;
            case R.id.btn_search:
                keyWord = main_search.getText().toString();
                getCateList(token, categoryId, main_search.getText().toString(), 1);

                break;
        }
    }

    public void popWindowCreate(List<GongYIngCateGoryModel.DataBean> dataBeanList) {
        popupWindow = new PopupWindowCompat(this);
        View contentView = LayoutInflater.from(this).inflate(R.layout.popgongying, null);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setContentView(contentView);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        TextView textView = contentView.findViewById(R.id.tv_kdd);
        textView.setText("");
        LinearLayout layout_content = contentView.findViewById(R.id.layout_content);
        layout_content.getBackground().setAlpha(180);
        SwipeRecyclerView recyclerView = contentView.findViewById(R.id.recycler_view);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        myLabelAdapter = new GongYIngAdapter(GongYingShangActivity.this, dataBeanList);
        recyclerView.setAdapter(myLabelAdapter);


        myLabelAdapter.setOnItemClickListener(new GongYIngAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(View view, int pos, List<GongYIngCateGoryModel.DataBean> myLiveList) {
                myLabelAdapter.setCheckedPosition(pos);
                categoryId = myLiveList.get(pos).getId();
                cateGroy = myLiveList.get(pos).getName();
                getCateList(token, myLiveList.get(pos).getId(), keyWord, pageNumber);
                text_Category.setText(myLiveList.get(pos).getName());
                popupWindow.dismiss();
            }


        });
        DividerItemDecoration divider = new DividerItemDecoration(GongYingShangActivity.this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(GongYingShangActivity.this, R.drawable.custom_divider));

        recyclerView.addItemDecoration(divider);
    }

    public void onEventMainThread(Integer integer) {
        if (integer == 6) {
            getCateList(token, categoryId, "", 1);
        }

    }

    @Override
    public void onItemClickListener(View view, int pos, List<GongYingListModel.DataBean> myLiveList) {
        Intent intent;
        switch (view.getId()) {
            case R.id.check_shop:

                break;
            default:
                intent = new Intent(GongYingShangActivity.this, SupplierShopActivity.class);
                intent.putExtra("supplierId", myLiveList.get(pos).getSupplierId());

                startActivity(intent);
        }
    }
}
